import 'dart:io';

import 'package:desktop_drop/desktop_drop.dart';
import 'package:excel_utils/extend/string_extend.dart';
import 'package:excel_utils/pages/cpc_report/bean/china_post_luggage_bean.dart';
import 'package:excel_utils/pages/cpc_report/cpc_luggage/bean/cpc_result_bean.dart';
import 'package:excel_utils/pages/cpc_report/bean/fee_item_bean.dart';
import 'package:excel_utils/pages/cpc_report/bean/luggeasy_bean.dart';
import 'package:excel_utils/pages/cpc_report/bean/waybill_managent_bean.dart';
import 'package:excel_utils/pages/cpc_report/cpc_luggage/bloc/cpc_report_bloc.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';


class CPCReportPage extends StatefulWidget {
  const CPCReportPage({super.key});

  @override
  State<CPCReportPage> createState() => _CPCReportPageState();
}

class _CPCReportPageState extends State<CPCReportPage> {
  CpcReportBloc? _cpcReportBloc;

  File? _waybillManagementFile;
  String? waybillManagementName;
  bool waybillManagementLoadingState = false;
  double waybillManagementProgress = 0.0;
  List<WaybillManagementBean> waybillManagementList = [];

  File? _chinaPostLuggageFile; // 中郵行李
  String? chinaPostLuggageName;
  bool chinaPostLuggageLoadingState = false;
  double chinaPostLuggageProgress = 0.0;
  List<ChinaPostLuggageBean> chinaPostLuggageList = [];

  File? _feeItemFile;
  String? feeItemName;
  bool feeItemLoadingState = false;
  double feeItemProgress = 0.0;
  List<FeeItemBean> feeItemList = [];

  File? _luggeasyFile;
  String? luggeasyName;
  bool luggeasyLoadingState = false;
  double progress = 0.0;
  List<LuggeasyBean> luggeasyList = [];

  List<String> headeData = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "aa", "ab"];
  List<CpcResultBean> cpcResultList = [];
  File? writeFile;
  String? writeName;
  bool writeFileLoadingState = false;
  double margeProgress = 0.0;

  showSnackBar(Text msg) {
    ScaffoldMessenger.of(context)..hideCurrentSnackBar()..showSnackBar(SnackBar(content: msg));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: BlocProvider<CpcReportBloc>(
        create: (BuildContext context) => CpcReportBloc(),
        child: BlocBuilder<CpcReportBloc, CpcReportState>(
          builder: (BuildContext context, CpcReportState state) {
            _cpcReportBloc = _cpcReportBloc ?? context.read<CpcReportBloc>();

            if (state is CpcWaybillManagementLoadingState) {
              waybillManagementLoadingState = true;
              waybillManagementProgress = state.progress;
            } else if (state is CpcWaybillManagementState) {
              waybillManagementLoadingState = false;
              waybillManagementList.clear();
              waybillManagementList.addAll(state.waybillManagementList);
            } else if (state is CpcChinaPostLuggageLoadingState) {
              chinaPostLuggageLoadingState = true;
              chinaPostLuggageProgress = state.progress;
            } else if (state is CpcChinaPostLuggageState) {
              chinaPostLuggageLoadingState = false;
              chinaPostLuggageList.clear();
              chinaPostLuggageList.addAll(state.chinaPostLuggageList);
            } else if (state is CpcFeeItemLoadingState) {
              feeItemLoadingState = true;
              feeItemProgress = state.progress;
            } else if (state is CpcFeeItemState) {
              feeItemLoadingState = false;
              feeItemList.clear();
              feeItemList.addAll(state.feeItemList);
            } else if (state is CpcLuggeasyLoadingState) {
              luggeasyLoadingState = true;
              progress = state.progress;
            } else if (state is CpcLuggeasyState) {
              luggeasyLoadingState = false;
              luggeasyList.clear();
              luggeasyList.addAll(state.luggeasyList);


            } else if (state is CpcDataMergeSuccessState) {
              cpcResultList.clear();
              cpcResultList.addAll(state.cpcResultList);
            } else if (state is CpcWriteFileLoadingState) {
              margeProgress = state.progress;
              writeFileLoadingState = true;
            }

            return _buildUI();
          },
        ),
      ),
      floatingActionButton: FloatingActionButton(
        child: BackButton(),
        onPressed: () {},
      ),
    );
  }

  Widget _buildUI() {
    return SingleChildScrollView(
      child: Container(
        child: Column(
          children: [
            Text(
              "注意，文件格式必须为xlsx格式",
              style: TextStyle(fontSize: 20, color: Colors.red),
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                Container(
                  width: 200,
                  height: 150,
                  child: Column(
                    children: [
                      Expanded(
                          child: DropTarget(
                              onDragDone: (data) {
                                // 判断是否为xlsx格式
                                // if (data.files.first.path.endsWith(".xlsx")) {
                                //   showSnackBar(Text("请选择   .xlsx 文件的格式"));
                                //   return;
                                // }
                                // 运单管理
                                _waybillManagementFile = File(data.files.first.path);
                                _cpcReportBloc?.add(CpcWaybillManagementEvent(file: _waybillManagementFile, sheetName: waybillManagementName ?? "Sheet1"));
                                // 开始解析
                                setState(() {});
                              },
                              child: Container(
                                color: Colors.blue.withOpacity(0.4),
                                child: _waybillManagementFile != null
                                    ? Text("${_waybillManagementFile!.path.split('\\').last}")
                                    : const Center(
                                        child: Text("運單管理，移动文件到此处"),
                                      ),
                              ))),
                      SizedBox(
                        height: 50,
                        child: TextField(
                          onChanged: (value) {
                            waybillManagementName = value;
                          },
                          decoration: InputDecoration(
                            hintText: "默认是Sheet1",
                            border: OutlineInputBorder(),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                Container(
                  width: 200,
                  height: 150,
                  child: Column(
                    children: [
                      Expanded(
                          child: DropTarget(
                              onDragDone: (data) {
                                // 判断是否为xlsx格式
                                // if (data.files.first.path.endsWith(".xlsx")) {
                                //   showSnackBar(Text("请选择   .xlsx 文件的格式"));
                                //   return;
                                // }
                                _chinaPostLuggageFile = File(data.files.first.path);
                                _cpcReportBloc?.add(CpcChinaPostLuggageEvent(file: _chinaPostLuggageFile, sheetName: chinaPostLuggageName ?? "Sheet1"));
                                setState(() {});
                              },
                              child: Container(
                                color: Colors.blue.withOpacity(0.4),
                                child: _chinaPostLuggageFile != null ? Text("${_chinaPostLuggageFile!.path.split('\\').last}") : const Center(child: Text("中郵行李，移动文件到此处")),
                              ))),
                      SizedBox(
                        height: 50,
                        child: TextField(
                          onChanged: (value) {
                            chinaPostLuggageName = value;
                          },
                          decoration: InputDecoration(
                            hintText: "默认是Sheet1",
                            border: OutlineInputBorder(),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                Container(
                  width: 200,
                  height: 150,
                  child: Column(
                    children: [
                      Expanded(
                        child: DropTarget(
                            onDragDone: (data) {
                              // 判断是否为xlsx格式
                              // if (data.files.first.path.endsWith(".xlsx")) {
                              //   showSnackBar(Text("请选择   .xlsx 文件的格式"));
                              //   return;
                              // }
                              _feeItemFile = File(data.files.first.path);
                              _cpcReportBloc?.add(CpcFeeitemlistEvent(file: _feeItemFile, sheetName: feeItemName ?? "Sheet1"));
                              setState(() {});
                            },
                            child: Container(
                              color: Colors.blue.withOpacity(0.4),
                              child: _feeItemFile != null ? Text("${_feeItemFile!.path.split('\\').last}") : const Center(child: Text("FeeItem，移动文件到此处")),
                            )),
                      ),
                      SizedBox(
                        height: 50,
                        child: TextField(
                          onChanged: (value) {
                            feeItemName = value;
                          },
                          decoration: InputDecoration(
                            hintText: "默认是Sheet1",
                            border: OutlineInputBorder(),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                Container(
                  width: 200,
                  height: 150,
                  child: Column(
                    children: [
                      Expanded(
                        child: DropTarget(
                            onDragDone: (data) {
                              // 判断是否为xlsx格式
                              // if (data.files.first.path.endsWith(".xlsx")) {
                              //   showSnackBar(Text("请选择   .xlsx 文件的格式"));
                              //   return;
                              // }
                              _luggeasyFile = File(data.files.first.path);
                              _cpcReportBloc?.add(CpcLuggeasyEvent(file: _luggeasyFile, sheetName: luggeasyName ?? "Sheet1"));
                              setState(() {});
                            },
                            child: Container(
                              color: Colors.blue.withOpacity(0.4),
                              child: _luggeasyFile != null ? Text("${_luggeasyFile!.path.split('\\').last}") : const Center(child: Text("Luggeasy，移动文件到此处")),
                            )),
                      ),
                      SizedBox(
                        height: 50,
                        child: TextField(
                          onChanged: (value) {
                            luggeasyName = value;
                          },
                          decoration: InputDecoration(
                            hintText: "默认是Sheet1",
                            border: OutlineInputBorder(),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
            Text("数据预览", style: TextStyle(fontSize: 20, color: Colors.red)),
            Container(
              decoration: BoxDecoration(border: Border.all(color: Colors.grey), borderRadius: BorderRadius.circular(10)),
              padding: EdgeInsets.all(10),
              margin: EdgeInsets.all(10),
              height: 160,
              child: SingleChildScrollView(
                child: Column(
                  children: [
                    Text("运单管理 ${waybillManagementList.length}"),
                    if (waybillManagementLoadingState) LinearProgressIndicator(value: waybillManagementProgress, color: Colors.blue),
                    Table(
                      children: [
                        const TableRow(children: [TableCell(child: Text("運單編號")), TableCell(child: Text("客戶名稱")), TableCell(child: Text("訂單地址")), TableCell(child: Text("入場時間"))]),
                        ...waybillManagementList.map((element) {
                          return TableRow(children: [
                            TableCell(child: Text("${element.waybillNumber}")),
                            TableCell(child: Text("${element.accountName}")),
                            TableCell(child: Text("${element.orderAddress}", maxLines: 1)),
                            TableCell(child: Text("${element.entryDate}")),
                          ]);
                        })
                      ],
                    ),
                  ],
                ),
              ),
            ),
            Container(
              decoration: BoxDecoration(border: Border.all(color: Colors.grey), borderRadius: BorderRadius.circular(10)),
              width: double.infinity,
              height: 160,
              padding: EdgeInsets.all(10),
              margin: EdgeInsets.all(10),
              child: SingleChildScrollView(
                child: Column(
                  children: [
                    Text("中邮数据 ${chinaPostLuggageList.length}"),
                    if (chinaPostLuggageLoadingState) LinearProgressIndicator(value: chinaPostLuggageProgress, color: Colors.blue),
                    Table(
                      children: [
                        TableRow(children: [TableCell(child: Text("TrackingNo")), TableCell(child: Text("LocalCurrentAction"))]),
                        ...chinaPostLuggageList.map((element) {
                          return TableRow(children: [TableCell(child: Text("${element.trackingNo}")), TableCell(child: Text("${element.localCurrentAction}"))]);
                        }),
                      ],
                    ),
                  ],
                ),
              ),
            ),
            Container(
              decoration: BoxDecoration(border: Border.all(color: Colors.grey), borderRadius: BorderRadius.circular(10)),
              width: double.infinity,
              height: 160,
              padding: EdgeInsets.all(10),
              margin: EdgeInsets.all(10),
              child: SingleChildScrollView(
                child: Column(
                  children: [
                    Text("FeeItem数据 ${feeItemList.length}"),
                    if(feeItemLoadingState) LinearProgressIndicator(value: feeItemProgress, color: Colors.blue),
                    Table(
                      children: [
                        TableRow(children: [TableCell(child: Text("跟踪号码")), TableCell(child: Text("重量(KG)")), TableCell(child: Text("费用"))]),
                        ...feeItemList.map((element) {
                          return TableRow(children: [TableCell(child: Text("${element.trackingNumber}")), TableCell(child: Text("${element.kg}")), TableCell(child: Text("${element.price}"))]);
                        })
                      ],
                    ),
                  ],
                ),
              ),
            ),
            Container(
              decoration: BoxDecoration(border: Border.all(color: Colors.grey), borderRadius: BorderRadius.circular(10)),
              width: double.infinity,
              height: 160,
              padding: EdgeInsets.all(10),
              margin: EdgeInsets.all(10),
              child: SingleChildScrollView(
                child: Column(
                  children: [
                    Text("FeeItem数据  ${luggeasyList.length}"),
                    if (luggeasyLoadingState) LinearProgressIndicator(value: progress, color: Colors.blue),
                    Table(
                      children: [
                        TableRow(children: [
                          TableCell(child: Text("日期")),
                          TableCell(child: Text("中郵運單號碼")),
                          TableCell(child: Text("重量(kg)")),
                          TableCell(child: Text("費用(港幣)")),
                          TableCell(child: Text("報關費(港幣)")),
                        ]),
                        ...luggeasyList.map((element) {
                          return TableRow(children: [
                            TableCell(child: Text("${element.date}")),
                            TableCell(child: Text("${element.cpOrderNo}")),
                            TableCell(child: Text("${element.kg}")),
                            TableCell(child: Text("${element.priceHKD}")),
                            TableCell(child: Text("${element.declarationPriceHKD}")),
                          ]);
                        })
                      ],
                    ),
                  ],
                ),
              ),
            ),
            Row(
              children: [
                SizedBox(
                  width: 10,
                ),
                ElevatedButton(
                    onPressed: () {
                      _cpcReportBloc?.add(CppDataMergeEvent(waybillManagementList: waybillManagementList, chinaPostLuggageList: chinaPostLuggageList, feeItemList: feeItemList, luggeasyList: luggeasyList));
                    },
                    child: Text("数据提取合并")),
                SizedBox(width: 10),
                ElevatedButton(
                    onPressed: () {
                      StringBuffer sb = StringBuffer();
                      for (var element in cpcResultList) {
                        sb.write("${element.a ?? ""}\t");
                        sb.write("${element.b ?? ""}\t");
                        sb.write("${element.c ?? ""}\t");
                        sb.write("${element.d ?? ""}\t");
                        sb.write("${element.e ?? ""}\t");
                        sb.write("${element.f ?? ""}\t");
                        sb.write("${element.g ?? ""}\t");
                        sb.write("${element.h ?? ""}\t");
                        sb.write("${element.i ?? ""}\t");
                        sb.write("${element.j ?? ""}\t");
                        sb.write("${element.k ?? ""}\t");
                        sb.write("${element.l ?? ""}\t");
                        sb.write("${element.m ?? ""}\t");
                        sb.write("${element.n ?? ""}\t");
                        sb.write("${element.o ?? ""}\t");
                        sb.write("${element.p ?? ""}\t");
                        sb.write("${element.q ?? ""}\t");
                        sb.write("${element.r ?? ""}\t");
                        sb.write("${element.s ?? ""}\t");
                        sb.write("${element.t ?? ""}\t");
                        sb.write("${element.u ?? ""}\t");
                        sb.write("${element.v ?? ""}\t");
                        sb.write("${element.w ?? ""}\t");
                        sb.write("${element.x ?? ""}\t");
                        sb.write("${element.y ?? ""}\t");
                        sb.write("${element.z ?? ""}\t");
                        sb.write("${element.aa ?? ""}\t");
                        sb.write("${element.ab ?? ""}\t");
                        sb.write("\n");
                      }
                      sb.toString().copyValue();
                    },
                    child: Text("允许复制或者右侧的写入")),
                SizedBox(width: 10),
                Container(
                  decoration: BoxDecoration(border: Border.all(color: Colors.grey), borderRadius: BorderRadius.circular(10)),
                  width: 200,
                  height: 100,
                  child: Column(
                    children: [
                      Expanded(
                          child: DropTarget(
                              onDragDone: (data) {
                                // 运单管理
                                writeFile = File(data.files.first.path);
                                setState(() {});
                              },
                              child: Container(
                                color: Colors.blue.withOpacity(0.4),
                                child: writeFile != null
                                    ? Center(
                                        child: Text("${writeFile!.path.split('\\').last}"),
                                      )
                                    : const Center(child: Text("拖动文件到此处")),
                              ))),
                      SizedBox(
                        height: 50,
                        width: 100,
                        child: TextField(
                            onChanged: (value) {
                              writeName = value;
                            },
                            decoration: InputDecoration(border: OutlineInputBorder(), labelText: "写入的文件名")),
                      ),
                    ],
                  ),
                ),
                SizedBox(
                  width: 10,
                ),
                ElevatedButton(
                    onPressed: () {
                      if (cpcResultList.isEmpty) {
                        showSnackBar(Text("请先提取数据"));
                      }
                      _cpcReportBloc?.add(CpcWriteFileEvent(cpcResultList: cpcResultList, writeFile: writeFile!, writeName: writeName.toString()));
                    },
                    child: Text("开始写入")),
              ],
            ),
            if (writeFileLoadingState)
              Center(
                child: LinearProgressIndicator(
                  value: margeProgress,
                  minHeight: 10,
                  borderRadius: BorderRadius.circular(10),
                ),
              ),
            Container(
              decoration: BoxDecoration(border: Border.all(color: Colors.grey), borderRadius: BorderRadius.circular(10)),
              width: double.infinity,
              height: 500,
              padding: EdgeInsets.all(10),
              margin: EdgeInsets.all(10),
              child: SingleChildScrollView(
                child: Column(
                  children: [
                    Text("数据合并结果"),
                    Table(
                      border: TableBorder.all(color: Colors.black),
                      children: [
                        TableRow(children: [...headeData.map((e) => TableCell(child: Text(e, textAlign: TextAlign.center)))]),
                        ...cpcResultList.map((element) {
                          return TableRow(children: [
                            TableCell(child: Container(alignment: Alignment.center, child: Text("${element.a ?? ""}"))),
                            TableCell(child: Container(alignment: Alignment.center, child: Text("${element.b ?? ""}", style: TextStyle(color: Colors.red), maxLines: 1))),
                            TableCell(child: Container(alignment: Alignment.center, child: Text("${element.c ?? ""}", style: TextStyle(color: Colors.red), maxLines: 1))),
                            TableCell(child: Container(alignment: Alignment.center, child: Text("${element.d ?? ""}", style: TextStyle(color: Colors.orange)))),
                            TableCell(child: Container(alignment: Alignment.center, child: Text("${element.e ?? ""}"))),
                            TableCell(child: Container(alignment: Alignment.center, child: Text("${element.f ?? ""}", style: TextStyle(color: Colors.red), maxLines: 1))),
                            TableCell(child: Container(alignment: Alignment.center, child: Text("${element.g ?? ""}", style: TextStyle(color: Colors.green)))),
                            TableCell(child: Container(alignment: Alignment.center, child: Text("${element.h ?? ""}"))),
                            TableCell(child: Container(alignment: Alignment.center, child: Text("${element.i ?? ""}", style: TextStyle(color: Colors.orange)))),
                            TableCell(child: Container(alignment: Alignment.center, child: Text("${element.j ?? ""}", style: TextStyle(color: Colors.blue)))),
                            TableCell(child: Container(alignment: Alignment.center, child: Text("${element.k ?? ""}"))),
                            TableCell(child: Container(alignment: Alignment.center, child: Text("${element.l ?? ""}"))),
                            TableCell(child: Container(alignment: Alignment.center, child: Text("${element.m ?? ""}", style: TextStyle(color: Colors.blue)))),
                            TableCell(child: Container(alignment: Alignment.center, child: Text("${element.n ?? ""}"))),
                            TableCell(child: Container(alignment: Alignment.center, child: Text("${element.o ?? ""}"))),
                            TableCell(child: Container(alignment: Alignment.center, child: Text("${element.p ?? ""}"))),
                            TableCell(child: Container(alignment: Alignment.center, child: Text("${element.q ?? ""}"))),
                            TableCell(child: Container(alignment: Alignment.center, child: Text("${element.r ?? ""}", style: TextStyle(color: Colors.orange)))),
                            TableCell(child: Container(alignment: Alignment.center, child: Text("${element.s ?? ""}"))),
                            TableCell(child: Container(alignment: Alignment.center, child: Text("${element.t ?? ""}"))),
                            TableCell(child: Container(alignment: Alignment.center, child: Text("${element.u ?? ""}"))),
                            TableCell(child: Container(alignment: Alignment.center, child: Text("${element.v ?? ""}"))),
                            TableCell(child: Container(alignment: Alignment.center, child: Text("${element.w ?? ""}"))),
                            TableCell(child: Container(alignment: Alignment.center, child: Text("${element.x ?? ""}"))),
                            TableCell(child: Container(alignment: Alignment.center, child: Text("${element.y ?? ""}"))),
                            TableCell(child: Container(alignment: Alignment.center, child: Text("${element.z ?? ""}"))),
                            TableCell(child: Container(alignment: Alignment.center, child: Text("${element.aa ?? ""}"))),
                            TableCell(child: Container(alignment: Alignment.center, child: Text("${element.ab ?? ""}"))),
                          ]);
                        })
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
